package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ReportMapper;
import com.sky.mapper.UserMapper;
import com.sky.result.Result;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 营业额统计接口
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result turnoverStatistics(LocalDate begin, LocalDate end) {
        //创建一个集合装获取每一天时间
        List<LocalDate> list = new ArrayList<>();
        //添加第一天时间
        list.add(begin);
        //添加时间
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            list.add(begin);
        }
        //定义一个list用来封装每一天的营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate localDate : list) {
            //获取当天的最小时间，年月日时分秒 00:00:00
            LocalDateTime min = LocalDateTime.of(localDate, LocalTime.MIN);
            //获取当天的最大时间，年月日时分秒 23:59:59
            LocalDateTime max = LocalDateTime.of(localDate, LocalTime.MAX);
            //调用mapper方法查出每天的营业额
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("min", min);
            map.put("max", max);
            Double aDouble = orderMapper.totalMoney(map);
            //注意，此时返回的turnover，有可能为null,如果为null,我们则赋值为0
            aDouble = aDouble == null ? 0 : aDouble;
            //添加到List中
            turnoverList.add(aDouble);
        }
        //封装turnoverList营业额dateList日期
        TurnoverReportVO vo = TurnoverReportVO.builder()
                .turnoverList(StringUtils.join(turnoverList, ","))
                .dateList(StringUtils.join(list, ","))
                .build();
        //返回
        return Result.success(vo);
    }

    /**
     * 用户统计接口
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result userStatistics(LocalDate begin, LocalDate end) {
        //创建一个集合装获取每一天时间
        List<LocalDate> list = new ArrayList<>();
        //添加第一天时间
        list.add(begin);
        //添加时间
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            list.add(begin);
        }
        //定义一个list用来装当天的新用户
        List<Integer> xinUserList = new ArrayList<>();
        //定义一个list用来装当天和以前的用户
        List<Integer> jiuUserList = new ArrayList<>();
        for (LocalDate localDate : list) {
            //获取当天的最小时间，年月日时分秒 00:00:00
            LocalDateTime min = LocalDateTime.of(localDate, LocalTime.MIN);
            //获取当天的最大时间，年月日时分秒 23:59:59
            LocalDateTime max = LocalDateTime.of(localDate, LocalTime.MAX);
            //调用mapper方法查出用户增加
            Map map = new HashMap();
            //查询mysql 获取当天的总用户数量
            map.put("max", max);
            Integer uSerList = userMapper.getUSerList(map);
            //查询mysql获取当天的新增用户数量
            map.put("min", min);
            Integer serList = userMapper.getUSerList(map);
            jiuUserList.add(uSerList);
            xinUserList.add(serList);
        }
        //3.返回数据
        UserReportVO vo = UserReportVO.builder()
                .dateList(StringUtils.join(list, ","))
                .newUserList(StringUtils.join(xinUserList, ","))
                .totalUserList(StringUtils.join(jiuUserList, ","))
                .build();
        return Result.success(vo);
    }

    /**
     * 订单统计接口
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result<OrderReportVO> ordersStatistics(LocalDate begin, LocalDate end) {
        //创建一个集合装时间
        ArrayList<LocalDate> dateList = new ArrayList<>();
        //添加初始时间
        dateList.add(begin);
        //循环
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            dateList.add(begin);
        }
        //创建一个集合装当天订单数
        ArrayList<Integer> orderCountList = new ArrayList<>();
        //创建一个集合装当天有效订单数
        ArrayList<Integer> validOrderCountList = new ArrayList<>();
        //创建一个变量装完成率
        Double orderCompletionRate=0.0;
        //遍历每一天时间
        for (LocalDate date : dateList) {
            //获取一天最大最小时间
            LocalDateTime min=LocalDateTime.of(date,LocalTime.MIN);
            LocalDateTime max=LocalDateTime.of(date,LocalTime.MAX);
            //创建map装时间
            Map map=new HashMap();
            map.put("min",min);
            map.put("max",max);
            //调用mapper拿到当天订单总数
            Integer totalOrderCount = orderMapper.getOrderCount(map);
            totalOrderCount=totalOrderCount==null ? 0:totalOrderCount;
            //调用mapper拿到当天有效订单数
            map.put("status",Orders.COMPLETED);
            Integer validOrderCount = orderMapper.getOrderCount(map);
            validOrderCount=validOrderCount==null ? 0:validOrderCount;
            orderCountList.add(totalOrderCount);
            validOrderCountList.add(validOrderCount);
        }
        //获取时间区间内的总订单数和有效订单数以及订单完成率
        //聚合求和总订单数
        Integer totalsum = orderCountList.stream().reduce(Integer::sum).get();
        //聚合求和有效订单数
        Integer validsum = validOrderCountList.stream().reduce(Integer::sum).get();
        //求完成率
        if (totalsum!=0){
            orderCompletionRate= validsum.doubleValue()/totalsum;
        }
        //进行封装
        OrderReportVO vo = OrderReportVO.builder()
                .orderCompletionRate(orderCompletionRate)
                .dateList(StringUtils.join(dateList,","))
                .totalOrderCount(totalsum)
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCount(validsum)
                .build();
        //返回
        return Result.success(vo);
    }

    /**
     * 查询销量排名top10接口
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result<SalesTop10ReportVO> topStatistics(LocalDate begin, LocalDate end) {
        //获取最大时间最小时间
        LocalDateTime min = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime max = LocalDateTime.of(end, LocalTime.MAX);
        //调用mapper
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(min,max);
        //获取商品名称列表通过所有stream()把name放入List集合中
        List<String> strings = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        //获取销量列表stream()把所有Number放入List集合中
        List<Integer> integers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        //封装进行StringUtils.join(strings, ",")把字符串用,拼接起来
        SalesTop10ReportVO vo = SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(strings, ","))
                .numberList(StringUtils.join(integers, ","))
                .build();
        //返回
        return Result.success(vo);
    }

    /**
     * 导出近30天的运营数据报表
     *
     * @param response
     * @return
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //设置要求多少时间的最大日期至最小日期
        LocalDate begin=LocalDate.now().minusDays(30);
        LocalDate end=LocalDate.now().minusDays(1);
        //查询概览运营数据，提供给Excel模板文件
        BusinessDataVO businessData = workspaceService.getBusinessData(
                LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
        //获取相对位置的文件  获取本类        线层工厂                位置                      具体文件位置
        InputStream in=this.getClass().getClassLoader().getResourceAsStream("XSSF/运营数据报表模板.xlsx");
        try {
            //基于提供好的模板文件创建一个新的Excel表格对象
            XSSFWorkbook workbook = new XSSFWorkbook(in);
            //获得Excel文件中的一个Sheet页
            XSSFSheet sheet = workbook.getSheet("Sheet1");
            //写入时间
            sheet.getRow(1).getCell(1).setCellValue(begin+"至"+end);
            //写入营业额
            sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
            //写入订单完成率
            sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            //写入新用户增加
            sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
            //写入有效订单
            sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
            //写入平均客单价
            sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());
            //写入明细数据
            for (int i = 0; i <30 ; i++) {
                //设置开始时间
                LocalDate date = begin.plusDays(i);
                //准备明细数据设置开始结束时间
                businessData=workspaceService.getBusinessData(
                        LocalDateTime.of(date,LocalTime.MIN),LocalDateTime.of(date,LocalTime.MAX));
                //获取行
                XSSFRow row = sheet.getRow(7 + i);
                //获取列并写入数据
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }
            //通过输出流将文件下载到客户端浏览器中
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            //关闭流
            outputStream.flush();
            outputStream.close();
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
